<template>
  <div v-loading="detailLoad" class="detail-card">
    <el-row justify="space-evenly">
      <div id="echartLine" class="echartDiv" ref="echartRef" style="width: 100%;height: 400px;"></div>
    </el-row>
    <el-row justify="center">
      <div style="display: flex; justify-content: center; align-items: center; width: 70%; ">
        <span style="width:50%; font-size: 18px; margin-right: 10%;text-align:right">总耗时</span>
        <span style="width:50%; font-size: 18px;"><strong style="color: #4caf50;"> {{ time }} </strong> 秒 </span>
      </div>
    </el-row>
    <el-row justify="center">
      <div style="display: flex; justify-content: center; align-items: center; width: 70%;">
        <span style="width:50%; font-size: 18px; margin-right: 10%;text-align:right">平均接口请求耗时</span>
        <span style="width:50%; font-size: 18px;"> <strong style="color: #4caf50;">{{ testResult.avgTime }}</strong> 毫秒</span>
      </div>
    </el-row>
    <el-row justify="center">
      <div style="display: flex; justify-content: center; align-items: center; width: 70%;">
        <span style="width:50%; font-size: 18px; margin-right: 10%;text-align:right">循环数</span>
        <span style="width:50%; font-size: 18px;"> {{ testResult.cycleNum }} </span>
      </div>
    </el-row>
    <el-row class="mt10" style="align-items: center;justify-content: center;margin-top:20px">
      <el-button type="warning" size="m" v-show="stopFlag" @click="stoptask" style="width:120px">终 止</el-button>
    </el-row>
    <el-row class="process-export-button" justify="center">
      <a v-if=" testResult.testCount === detail.count" style="font-size: 20px; color: #b399f7;" @click="exportReport">导出报告
        <el-icon style="font-size: 16px; vertical-align: middle;">
          <Download/>
        </el-icon>
      </a>
    </el-row>
    <!-- <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <Fail v-if="failView" ref="failRequest" :failMap="failMap"/>
    </el-row>
   <el-row v-model="curveShow" style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <Curve ref="lineChartCpuForm" :chartData="lineChartCpuData"/>
      <Curve ref="lineChartMenForm" :chartData="lineChartMenData"/>
    </el-row>-->
  </div>
</template>

<script setup expose name="detail">
import * as echarts from 'echarts';
import {onMounted, nextTick, onUnmounted, watch, reactive} from 'vue';
import Curve from "@/views/testmanage/onekeysst/monitorCurve";
import Fail from "@/views/testmanage/onekeysst/component/failRequestView";
import * as components from '@element-plus/icons-vue'
import {defineExpose} from 'vue'
import useTestResultStore from '@/store/modules/testResult'
import {isNotVoid, isVoid} from "@/utils/util";
import {
  queryCalcServerCurve
} from "@/api/testmanage/calcServer";

import {
  stopRunTask, queryInfResultTimer, stopRecord
} from "@/api/testmanage/autoTest";

import useResizeDom from '@/utils/useResizeDom.js'

const resizeObserver = useResizeDom();
const {proxy} = getCurrentInstance();
const curveShow = ref(false);
const lineChartCpuData = ref({});
const lineChartMenData = ref({});
const timer = ref(null);
const resultTimer = ref(null);
const timerRunning = ref(false);
const monitorServe = ref(false);
const stopFlag = ref(true);
const time = ref(0);
const tabPosition = ref('');
const seriesCpuNames = ref([]);
const seriesMenNames = ref([]);
const curveCpuNames = ref([]);
const curveMenNames = ref([]);
//是否终止运行
const stopRun = ref(false);
//失败接口
const failMap = reactive(new Map())
const failView = ref(false);


const data = reactive({
  dataList: [
    {value: 0, name: '通过'},
    {value: 0, name: '失败'},
    {value: 0, name: '未测'}
  ],
  testResult: {
    testCount: 0,
    consumeTime: 0,
    avgTime: 0,
    cycleNum: 0
  },
  detail: {
    reportId: '',
    count: 0,
    threadNumber: 0,
    infLength: 0,
    mcs: ''
  }
})
const {testResult, detail, dataList} = toRefs(data);

const props = defineProps({
  detailLoad: {
    type: Boolean,
    default: false
  },
})

watch(dataList, (nv, ov) => {
  echartInit()
}, {deep: true})

watch(monitorServe, (nv, ov) => {
  if (nv === true) {
    handleCurve()
  }
})
// 请求获取过程
/*const queryResultTimer = () => {
    queryInfResultTimer(detail.value.reportId).then(response => {
        let res = response.result
        let list = res.list
        testResult.value.testCount += list.length
        dataList.value[2].value -= list.length
        list.forEach(item => {
            testResult.value.consumeTime += item.consumeTime
            if (item.status == "0") {
                dataList.value[0].value += 1
            } else {
                failView.value = true
                if(Array.from(failMap.keys()).includes(item.infId)) {
                    let fail = failMap.get(item.infId)
                    fail.count += 1
                    if (item.errorType == 1) {
                        fail.timeOutCount += 1
                    } else {
                        fail.commonErrCount += 1
                    }
                } else {
                    item.count = 1
                    if (item.errorType == 1) {
                        item.timeOutCount = 1
                        item.commonErrCount = 0
                    } else {
                        item.timeOutCount = 0
                        item.commonErrCount = 1
                    }
                    failMap.set(item.infId, item)
                }
                dataList.value[1].value += 1
            }
        })
        testResult.value.avgTime = testResult.value.testCount == 0 ? 0 : proxy.lsh.divide(testResult.value.consumeTime, testResult.value.testCount).toFixed(2)
        testResult.value.cycleNum = Math.ceil(testResult.value.testCount / (detail.value.infLength * detail.value.threadNumber))
        if (res.isDone == 1) {
            stopTimer()
            stopFlag.value = false
            if (detail.value.mcs) {
                monitorServe.value = true
            }
            time.value = res.totalTime
            clearInterval(resultTimer.value);
        }
    })
}*/

// zip.li 2023-09-25 修改获取测试过程， 使用netty
watch(useTestResultStore().map, (nv, ov) => {
  let data = useTestResultStore().getResult(detail.value.reportId)
  if (isNotVoid(data)) {
    if (isNotVoid(data.totalTime)) {
      stopTimer()
      stopFlag.value = false
      if (detail.value.mcs) {
        monitorServe.value = true
      }
      time.value = data.totalTime
      return
    }
    testResult.value.testCount += 1
    dataList.value[2].value -= 1
    if (data.status === "200") {
      dataList.value[0].value += 1
    } else {
      dataList.value[1].value += 1
    }
    testResult.value.consumeTime += data.consumeTime
    testResult.value.avgTime = proxy.lsh.divide(testResult.value.consumeTime, testResult.value.testCount).toFixed(2)
    testResult.value.cycleNum = Math.ceil(testResult.value.testCount / (detail.value.infLength * detail.value.threadNumber))

    if (testResult.value.testCount === detail.value.count) {
      stopTimer()
      stopFlag.value = false
    }
  }
}, {deep: true})

const startTimer = () => {
  timerRunning.value = true;
  timer.value = setInterval(() => {
    time.value += 1
  }, 1000);

};

const stopTimer = () => {
  timerRunning.value = false;
  clearInterval(timer.value);
};

const resetTimer = () => {
  time.value = 0;
};

watch(timerRunning, (newVal) => {
  if (!newVal) {
    clearInterval(timer.value);
  }
});

onMounted(() => {
  nextTick(() => {
    echartInit()
  })
})
onUnmounted(() => {
  //clearInterval(resultTimer.value);
})

const myChart = ref(null);
const echartInit = () => {

  // 指定图表的配置项和数据
  let text = stopRun.value ? '已终止' : dataList.value[2].value == 0 ? '已完成' : '运行中';
  let option = {
    animation: false,
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal',
      left: 'center', // Set the legend position to the right side
      top: '5%',
      data: [
        {name: '通过'},
        {name: '失败'},
        {name: '未测'},
      ],
      itemGap: 20,
      itemWidth: 30,
      itemHeight: 20,
      fontWeight: 'bold',
      textStyle: { //图例文字的样式
        fontSize: 14,
        color: '#919191',
      },
      formatter: (name) => {
        let total = detail.value.count
        let value = dataList.value.filter(x => x.name == name)[0].value
        let arr = [
          name +
          '   ' + ((value / total) * 100).toFixed(2) + ' %' +
          '   ' + value
        ]
        return arr.join('\n')
      },

    },
    series: [
      {
        name: '测试结果',
        type: 'pie',
        radius: ['60%', '80%'],
        top: '10%',
        avoidLabelOverlap: false,
        itemStyle: {
          normal: {
            color: function (params) {
              // 自定义颜色数组
              var colorList = ['#62dcae', '#f97190', '#e2e2e2'];
              return colorList[params.dataIndex]
            }
          },
          borderRadius: 10,
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'center',
          formatter: '{a|' + text + '}\n{b|' + (testResult.value.testCount) + '}',
          rich: {
            a: {
              fontSize: 20,
              lineHeight: 24
            },
            b: {
              fontSize: 30,
              fontWeight: 'bold',
              lineHeight: 36
            }
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: dataList.value
      }
    ]
  };

  if (!myChart.value) {
    myChart.value = echarts.init(proxy.$refs.echartRef);
  }
  // 使用刚指定的配置项和数据显示图表。
  myChart.value.setOption(option);
}
onMounted(() => {
  resizeObserver.observe(proxy.$refs.echartRef, resizeChart)
})
onUnmounted(() => {
  // 页面销毁时卸载echarts
  disposeChart();
})
const resizeChart = () => {
  myChart.value?.resize()
}
const disposeChart = () => {
  myChart.value?.dispose()
  myChart.value = null
}

/** 查看曲线按钮操作 */
function handleCurve() {
  const data = {
    reportId: detail.value.reportId
  }
  queryCalcServerCurve(data).then(response => {
    if (response.code != '-1') {
      curveShow.value = true
      let listData = response.result
      let addressSet = new Set();
      let timeSet = new Set();
      listData.forEach(function (obj) {
        addressSet.add(obj.address)
        timeSet.add(obj.getTime)
      });
      const array = Array.from(timeSet);
      const sortedArray = array.sort();
      seriesCpuNames.value = ['systemCpuUsed']
      seriesMenNames.value = ['usedMemory']
      proxy.$refs.lineChartCpuForm.initChart()
      proxy.$refs.lineChartCpuForm.setChartData(proxy, '计算服务CPU使用', response.result, 'getTime', seriesCpuNames.value, addressSet, Array.from(addressSet), "时间", "CPU使用率(%)", sortedArray);
      proxy.$refs.lineChartMenForm.setChartData(proxy, '计算服务内存使用', response.result, 'getTime', seriesMenNames.value, addressSet, Array.from(addressSet), "时间", "内存使用率(%)", sortedArray);
    } else {
      proxy.$modal.msgError(response.msg);
    }

  });
}

const exportReport = () => {
  proxy.$emit('handleExport', detail.value.reportId)
}

const resetData = () => {
  stopRecord(detail.value.reportId)
  testResult.value = {
    consumeTime: 0,
    testCount: 0,
    avgTime: 0,
    cycleNum: 0
  }
  dataList.value = [
    {value: 0, name: '通过'},
    {value: 0, name: '失败'},
    {value: 0, name: '未测'}
  ],
      detail.value = {
        reportId: '',
        count: 0,
        threadNumber: 0,
        infLength: 0
      }
  /*resetTimer()*/
  if (curveShow.value) {
    curveShow.value = false
    proxy.$refs.lineChartCpuForm.clearCharData()
    proxy.$refs.lineChartMenForm.clearCharData()
  }
  monitorServe.value = false
}

const getDetail = (reportId, count, threadNumber, infLength, mcs) => {
  detail.value.reportId = reportId
  detail.value.count = count
  dataList.value[2].value = count
  detail.value.threadNumber = threadNumber
  detail.value.infLength = infLength
  detail.value.mcs = mcs
}

const stoptask = () => {
  var data = detail.value.reportId
  stopRunTask(data).then(response => {
    proxy.$modal.msgSuccess(response.result);
    stopRun.value = true
    echartInit()
    stopTimer()
    //clearInterval(resultTimer.value);
  });
}

defineExpose({
  startTimer, getDetail, resetData, stopFlag, stopRun
})

</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.detail-card {
  /* padding: 20px 20px ; */
}

.process-export-button {
  margin-top: 25px;
  margin-bottom: 15px;
}

.process-item-first {
  height: 18px;
}

.process-item-container {
  display: inline-grid;
}

/deep/ .el-result {
  --el-result-padding: 0px 0px !important;
  --el-result-icon-font-size: 16px !important;
  --el-result-title-font-size: 16px !important;
  --el-result-title-margin-top: 16px !important;
  --el-result-subtitle-margin-top: 16px !important;
  --el-result-extra-margin-top: 16px !important;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}

.detail-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
}

.page-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  height: 100px;
}

.field-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.field-label {
  margin-right: 10px;
  font-weight: bold;
}

.field-value {
  font-size: 18px;
}

</style>